<template>
  <div style="height: 100vh; width: 100%">
    <common-bg-blue1></common-bg-blue1>
    <div style="position: absolute; right: 10px; top: 5px; z-index: 1000">
      <common-back @clicked="closePopup"></common-back>
    </div>
    <div
      style="
        display: flex;
        width: 100%;
        justify-content: center;
        flex-direction: column;
        align-items: center;
        padding: 16px;
      ">
      <div
        style="
          width: 100%;
          border-radius: 8px 8px 8px 8px;
          height: 53px;
          background: #ffffff;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 8px;
        ">
        <div class="tab-zixundan" :style="styleZiXunDanG" @click="swhZixundan(2)">顾客咨询单</div>
        <div class="tab-zixundan" :style="styleZiXunDanC" @click="swhZixundan(1)">参考咨询单</div>
      </div>
      <div v-if="FlagZiXunDan === 1" style="width: 100%">
        <van-loading
          v-if="picZiXunDanC != undefined && picZiXunDanC.length < 10"
          color="#1989fa"
          vertical
          style="align-items: center; margin: auto">
          加载中...
        </van-loading>
        <img v-else alt="参考咨询单" :src="picZiXunDanC" width="100%" @click.stop="handlePreviewImg(1)" />
      </div>
      <div v-else style="width: 100%">
        <van-loading
          v-if="picZiXunDanG != undefined && picZiXunDanG.length < 10"
          color="#1989fa"
          vertical
          style="align-items: center; margin: auto">
          加载中...
        </van-loading>
        <img v-else alt="顾客咨询单" :src="picZiXunDanG" width="100%" @click.stop="handlePreviewImg(2)" />
      </div>
      <div
        class="btn-zixundan"
        :style="{
          background: '#766AFF',
          color: '#ffffff',
          cursor: 'pointer',
        }"
        @click="downloadZixundan()">
        下载咨询单
        <van-loading v-if="isZiXunDanDnld" color="#ffffff"></van-loading>
      </div>
      <div
        class="btn-zixundan"
        :style="{
          background: 'none',
          color: '#666666',
        }"
        @click="closePopup">
        返回
      </div>
    </div>

    <van-image-preview v-model="isPreviewZiXun" :images="previewImages" closeable @change="handlePreviewChange">
      <template v-slot:index>
        <span style="color: aquamarine">{{ previewTitle }}</span>
      </template>
    </van-image-preview>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { getZiXunDanPdf, getZiXunDanPic } from '@/api/txs';
// 引入自定义组件
import CommonBack from '@/components/back/index.vue';
import CommonBgBlue1 from '@/components/bg/Blue1.vue';
// 引入第三方组件
import { ImagePreview, Notify } from 'vant';

export default {
  name: 'Zixundan',
  components: {
    ['common-back']: CommonBack,
    ['common-bg-blue1']: CommonBgBlue1,
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  props: {},
  data() {
    return {
      consumerId: undefined,
      FlagZiXunDan: 1,
      picZiXunDanC: '',
      picZiXunDanG: '',
      isZiXunDanDnld: false,
      isPreviewZiXun: false,
      previewImages: [],
      previewTitle: '',
      styleZiXunDanC: {},
      styleZiXunDanG: {},
    };
  },
  created() {
    // this.swhZixundan(2);
  },
  mounted() {
    // this.swhZixundan(2);
  },
  methods: {
    closePopup() {
      this.$emit('close');
    },
    handlePreviewImg(val) {
      const tmp = [];
      switch (val) {
        case 1:
          tmp.push(this.picZiXunDanC);
          break;
        case 2:
          tmp.push(this.picZiXunDanG);
          break;
        default:
          return;
      }
      this.previewImages = tmp;
      this.isPreviewZiXun = true;
    },
    handlePreviewChange(idx) {},
    // van-popup 只会创建一次，所以需要在打开时重新加载数据
    loadZiXunDan: async function (consumerId) {
      this.consumerId = consumerId;
      this.picZiXunDanC = '';
      this.picZiXunDanG = '';
      this.swhZixundan(2);
    },
    swhZixundan: async function (val) {
      this.FlagZiXunDan = val;
      this.isZiXunDanDnld = false;
      switch (this.FlagZiXunDan) {
        case 1:
          this.styleZiXunDanG.background = 'none';
          this.styleZiXunDanC.background = '#ECEBFF';
          if (!!this.picZiXunDanC && this.picZiXunDanC.length > 0) {
            return;
          }
          this.picZiXunDanC = '';
          break;
        case 2:
          this.styleZiXunDanG.background = '#ECEBFF';
          this.styleZiXunDanC.background = 'none';
          if (!!this.picZiXunDanG && this.picZiXunDanG.length > 0) {
            return;
          }
          this.picZiXunDanG = '';
          break;
        default:
          return;
      }
      const errAlertMsg = '生成咨询单失败, 可能图片丢失了';
      getZiXunDanPic(this.consumerId, this.FlagZiXunDan)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              Notify({ type: 'danger', message: res.data.message });
            } else {
              Notify({ type: 'danger', message: errAlertMsg });
            }
            return;
          }
          const picBase64 = res.data.data;
          {
            if (!picBase64 || picBase64.length === 0) {
              picBase64 = undefined;
              Notify({ type: 'danger', message: errAlertMsg });
            }
            switch (this.FlagZiXunDan) {
              case 1:
                this.picZiXunDanC = picBase64;
                break;
              case 2:
                this.picZiXunDanG = picBase64;
                break;
              default:
                break;
            }
          }
        })
        .catch(err => {
          console.log('getZiXunDanPic error', err);
          Notify({ type: 'danger', message: errAlertMsg });
        });
    },
    downloadZixundan() {
      if (this.isZiXunDanDnld) {
        return;
      }
      if (this.FlagZiXunDan == 1 && (!this.picZiXunDanC || this.picZiXunDanC.length < 1)) {
        Notify({ type: 'danger', message: '咨询单还未生成' });
        return;
      }
      if (this.FlagZiXunDan == 2 && (!this.picZiXunDanG || this.picZiXunDanG.length < 1)) {
        Notify({ type: 'danger', message: '咨询单还未生成' });
        return;
      }
      this.isZiXunDanDnld = true;
      getZiXunDanPdf(this.consumerId, this.FlagZiXunDan).then(res => {
        this.isZiXunDanDnld = false;
        if (res.status !== 200) {
          Notify({ type: 'danger', message: '下载失败' });
          return;
        }
        this.exportFile(res);
      });
    },
    exportFile(result) {
      const contentDisposition = result.headers['content-disposition'];
      const filename = decodeURI(contentDisposition.split('fileName=')[1] || contentDisposition.split('filename=')[1]);
      const blobObj = new Blob([result.data], { type: result.headers['content-type'] });
      const url = window.URL.createObjectURL(blobObj);
      if (window.navigator.msSaveBlob) {
        try {
          window.navigator.msSaveBlob(blobObj, filename);
        } catch (e) {
          console.log(e);
        }
      } else {
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
      }
      URL.revokeObjectURL(url);
    },
  },
};
</script>

<style scoped>
.tab-zixundan {
  background: #ecebff;
  color: #766aff;
  width: 50%;
  height: 70px;
  border-radius: 6px 6px 6px 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 400;
  font-size: inherit;
  letter-spacing: 3px;
}
.btn-zixundan {
  background: none;
  color: #766aff;
  width: 100%;
  height: 70px;
  border-radius: 6px 6px 6px 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 400;
  font-size: inherit;
  letter-spacing: 3px;
}
</style>
